package com.qyhl.module_practice.volunteer.newlist.search;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeVolunteerBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_VOL_SEARCH)
public class PracticeVolSearchActivity extends BaseActivity implements PracticeVolSearchContract.PracticeVolSearchView {
    @BindView(R2.id.search_btn)
    TextView searchBtn;
    @BindView(R2.id.search_txt)
    EditText searchTxt;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private PracticeVolSearchPresenter mPresenter;

    private CommonAdapter<PracticeVolunteerBean> commonAdapter;

    private List<PracticeVolunteerBean> mDataList = new ArrayList<>();

    private int page = 1;

    private String keyWord = "";

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_vol_search;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyText("输入关键字搜索志愿者");
        mPresenter = new PracticeVolSearchPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new GridLayoutManager(this, 2));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeVolunteerBean>(this, R.layout.practice_item_volunteer_new, mDataList) {
            @Override
            protected void convert(ViewHolder holder, PracticeVolunteerBean bean, int position) {
                holder.setVisible(R.id.top_tag, false);

                holder.setText(R.id.name, "姓名：" + bean.getName());

                if (bean.getOrgs() != null && bean.getOrgs().size() > 0) {
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < bean.getOrgs().size(); i++) {
                        if (i == 0) {
                            stringBuilder.append(bean.getOrgs().get(i).getName());
                        } else {
                            stringBuilder.append(",").append(bean.getOrgs().get(i).getName());
                        }

                    }
                    holder.setText(R.id.organization, "服务队：" + stringBuilder.toString());
                } else {
                    holder.setText(R.id.organization, "服务队：无");
                }

                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(PracticeVolSearchActivity.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);

                holder.setVisible(R.id.level_tag, true);
                switch (bean.getLevel()) {
                    case 0:
                        holder.setVisible(R.id.level_tag, false);
                        break;
                    case 1:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv1_icon);
                        break;
                    case 2:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv2_icon);
                        break;
                    case 3:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv3_icon);
                        break;
                    case 4:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv4_icon);
                        break;
                    case 5:
                        holder.setImageResource(R.id.level_tag, R.drawable.practice_vol_lv5_icon);
                        break;
                        default:
                            break;
                }
            }
        });
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.doSearch(keyWord, page + "");
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.doSearch(keyWord, page + "");
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.doSearch(keyWord, page + "");
            }
        });

        searchTxt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyWord = s.toString();
                if (StringUtils.isNotEmpty(s.toString()) && s.toString().trim().length() > 0) {
                    searchBtn.setText("搜索");
                } else {
                    searchBtn.setText("取消");
                }
            }
        });

        searchTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//按下搜索
                    keyWord = searchTxt.getText().toString();
                    page = 1;
                    mPresenter.doSearch(keyWord, page + "");
                    hideKeyboard(v.getWindowToken());
                }
                return false;//返回true，保留软键盘。false，隐藏软键盘
            }

        });
    }

    @Override
    public void setSearchList(List<PracticeVolunteerBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                showToast("暂无更多志愿者！");
            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }


    @OnClick({R2.id.back_btn, R2.id.search_btn, R2.id.search_delete})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.back_btn) {
            finish();
        } else if (id == R.id.search_btn) {
            if (searchBtn.getText().toString().equals("搜索")) {
                if (StringUtils.isNotEmpty(keyWord)) {
                    page = 1;
                    mPresenter.doSearch(keyWord, page + "");
                } else {
                    showToast("搜索内容不能为空！");
                }
            } else {
                finish();
            }
        } else if (id == R.id.search_delete) {
            searchTxt.setText("");
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_VOL_SEARCH);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_VOL_SEARCH);
    }
}
